package com.jacobson.huobi.mvp

import android.app.Activity
import android.app.KeyguardManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.WindowManager
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.mvp.others.ScreenListener
import com.jacobson.huobi.utils.KeepLiveManager

/**
 * 单像素Activity，应用保活使用
 */
class OnePXActivity : Activity(), ScreenListener.ScreenStateListener {
    private val logger = LoggerFactory.getLogger()
    private lateinit var screenListener: ScreenListener
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //去掉系统锁屏页
        //使Activity在锁屏时仍然能够显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
            keyguardManager.requestDismissKeyguard(this, object:
                KeyguardManager.KeyguardDismissCallback() {
            })
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)
            window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
        }
        window.setGravity(Gravity.START or Gravity.TOP)
        // 启动左上角一像素视图
        val params = window.attributes
        params.x = 0
        params.y = 0
        params.height = 1
        params.width = 1
        window.attributes = params
        // 监听锁屏状态
        screenListener = ScreenListener(this)
        screenListener.begin(this)
        KeepLiveManager.storeOnePxActivity(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 反注册
        screenListener.unregisterListener()
    }

    override fun onScreenOn() {
        // 解锁时关闭
        logger.d("系统解锁锁屏，关闭1像素保活...")
        finish()
    }

    override fun onScreenOff() {
    }

    override fun onUserPresent() {
        logger.d("系统...")
        finish()
    }

}